package com.baiducloud.dawnoct.mysdk;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.fusingdata.UtilsQR.HexUtils;
import com.fusingdata.UtilsQR.JsonUtil;
import com.fusingdata.UtilsQR.QRutils;
import com.google.gson.Gson;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends Activity {

    ImageView mImageView;
    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView = (ImageView) findViewById(R.id.imageView);
        editText = (EditText) findViewById(R.id.edt);
    }

    //生成密钥对,
    public void generateKey(final View view) throws Exception {
        QRutils.generateKey(new QRutils.GenerateKeyCallBack() {
            @Override
            public void onSaveResult(boolean success, final String key) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "密钥对生成成功!", Toast.LENGTH_SHORT).show();
                        Log.e("MainActivity", "密钥对生成成功:" + key);
                    }
                });
            }
        });
    }


    //写入签名
    String jsonData = "";

    public void writeSignature(View view) {
        String json = "{\n" +
                "    \"data\": {\n" +
                "        \"qrversion\": 1,\n" +
                "        \"cer\": \"6A9C4380DA8FB37F2061D5DCE2E6E34E105A4E653E9D30B9C558C5C09F5FD67EAD5C61B3F484A45003C9FAE4B6B3CE5BD1246E1953C7F2ED876DBA3C4D900ED50CB420D5ABE7503EC762C5F4E2245F9FB18F9C82131B9AC18C9A8514FEB633C1476E7AB0388193545360C1C5797A663C46A4F81D8B0E3BD9DCFD9BBA3FBF3CD581FDBE5C0B4EED713365F866D86ECB2EDE03E532E2399484939909\",\n" +
                "        \"keyCer\": \"434552540101010101A72E02EDBA39324D236649C60800036A1B2AF9D5C4E6B6D692E71DC61607C958D2A32E087775DEA91F4252B3C6B6225F77B4F855860B0966F72DEBECF5569BDC7C00860AF7C0EFDF4C55410048D62E8AED2BA8799E4AD5093AE332E8BF1EBDFFDF78150D0ED30E78C4223A4A91035F2800DAB0771ECDB35153030CF44B095D6D5F55AA145F4A19EA3F6E42DB659DEF7441B6C4E0E111EF09A56BF9EA77EEFF52D6CEE9785B7B16931E153D7481C1F9D89DC4B12B2A0ABDC50EED0E2D1E99EE34E99A674AA6BC92CD71C9AFB6B6DDC720FE821BF86709B0414511CEBD663E2B93B5EDA0F94A903FE0881AB754D5F427683B4B02A15FD7B74594FA7C0DAFB3283D\",\n" +
                "        \"keyVersion\": 129\n" +
                "    },\n" +
                "    \"msg\": \"success\",\n" +
                "    \"result\": \"0000\"\n" +
                "}";
        if (TextUtils.isEmpty(jsonData)) {
            Toast.makeText(MainActivity.this, "用户证书不能为空, 请先请求用户证书!", Toast.LENGTH_SHORT).show();
            return;
        }
        String data = JsonUtil.getFieldValue(jsonData, "data");
        QRutils.writeUserCert(data, new QRutils.WriteUsertCertCallBack() {
            @Override
            public void onResult(final boolean success, final int code) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (success) {
                            Toast.makeText(MainActivity.this, "成功写入签名!", Toast.LENGTH_SHORT).show();
                            Log.e("MainActivity", "写入签名成功");
                        } else {
                            Toast.makeText(MainActivity.this, "写入签名失败!错误码为" + code, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
        //发码方最终签名
//        String signatureFinal = "268081F2A8451320C31BC0CF8C156A97EFFA8E8E3AA2222E0A4E9FCF358FAC395FA03729704646581895BD07FBE4AB4D0E4F6F7688588944F009D331A2A2A4FBAE88C6034846C8FD3FDD68C7CCBDD026048CC8BDA3A58324A72E3E1CF27B26F7DB2A5A1523A61A3A87ABED0B0FD02CDAF4B3AB368F8F6C46E3CB44609ACF5CAB81FDBE5C0B4EED713365F866D86ECB2EDE03E532E2399484939909";
//        String N = "BBBC49996CB668B80A83E6BD5DC98937334315E46AD46C09DAEBDF7E57FFAA30FB9C7D130E87CA06BED60E07648F0109D117A97F0D406DCC5D1F5FE63315151F2A5221B054474E16166F64E76053FF8C5C7A8C950109E3F820ED0505D7A4C7B4F24FD57EC09F8052E35A84255EEEF693A51BDC1819C29ECF2D439AE48CA08657";
//        String E = "00010001";
//        //todo 以上为模拟的数据
//        QRutils.writeUserCertTest(signatureFinal, N, new QRutils.WriteUsertCertCallBack() {
//            @Override
//            public void onResult(final boolean success) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (success) {
//                            Toast.makeText(MainActivity.this, "成功写入签名!", Toast.LENGTH_SHORT).show();
//                            Log.e("MainActivity", "写入签名成功");
//                        } else {
//                            Toast.makeText(MainActivity.this, "写入签名失败!", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });
//            }
//        });
    }

    //查找签名
    public void findSignature(View view) {
        QRutils.findSignatrueAsyn(new QRutils.FindUsertCertCallBack() {
            @Override
            public void onSuccess(final long validTime) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "签名的有效时长为:" + validTime + "毫秒", Toast.LENGTH_SHORT).show();
                        Log.e("MainActivity", "查询签名的剩余有效时长为:" + validTime + "毫秒");
                    }
                });

            }

            @Override
            public void onFail(final int f) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("MainActivity", f + "");
                        Toast.makeText(MainActivity.this, "查找签名失败:", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
    }

    //生成乘车二维码
    public void generateQR(View view) {
        String userData = "00000000FFFF000000000000000001017FFFFFFF010203040506070809000102030405060708090001020304050607080900";
        QRutils.generateQR(userData, "01", new QRutils.QRCallBack() {
            @Override
            public void onResult(final String qrContent, final int errorCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (TextUtils.isEmpty(qrContent)) {
                            Toast.makeText(MainActivity.this, "生成失败,错误码为" + errorCode, Toast.LENGTH_SHORT).show();
                        } else {
                            int l = HexUtils.hexStringToBytes(qrContent).length;
                            Toast.makeText(MainActivity.this, "二维码生成成功,内容字节长度为:" + l, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
//        Log.e("MainActivity", "二维码内容为: " + qrContent);

//        byte[] bytes = HexUtils.hexStringToBytes(qrContent);
//        int df = bytes.length;
//        int length = qrContent.length();
//        int ff = "0101010100FB268081F2A8451320C31BC0CF8C156A97EFFA8E8E3AA2222E0A4E9FCF358FAC395FA03729704646581895BD07FBE4AB4D0E4F6F7688588944F009D331A2A2A4FBAE88C6034846C8FD3FDD68C7CCBDD026048CC8BDA3A58324A72E3E1CF27B26F7DB2A5A1523A61A3A87ABED0B0FD02CDAF4B3AB368F8F6C46E3CB44609ACF5CAB81FDBE5C0B4EED713365F866D86ECB2EDE03E532E239948493990906BE150FF53E7BA8BB0AB2F5C48F4EE1D09022E784642BD65AD47B802C531AA2DDBE1792E9C253EFECA6540CBF0CE840DEAFD84B8F6FD4FE3F7E78D2A876970718E19D38F5D3C8435AAFF978A36AC053E3631294F735464C240A1EAF5A4395AE".length();
//        Log.e("MainActivity", "二维码内容为: " + qrContent);
    }

    public void generateUserCert(View view) {
        netData();
    }

    //请求网络数据
    public void netData() {
        //获得用户公钥
        QRutils.generateKey(new QRutils.GenerateKeyCallBack() {
            @Override
            public void onSaveResult(boolean success, String key) {
                String url = "http://202.100.241.142:17070/traffic_ca/ca/cer/issue";
                OkHttpClient okHttpClient = new OkHttpClient();
                RequstBean requstBean =
                        new RequstBean("0102030405060708090A", "11223344556677889900"
                                , "59f056d7", "00100000"
                                , "01", key, "01");
                Gson gson = new Gson();
                String requestJson = gson.toJson(requstBean);
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, requestJson);
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    jsonData = response.body().string();
                    String ff = "";
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "请求用户证书成功:", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }

}
